import { beisenAdapter } from './adapters/beisenAdapter';
import type { ResumeData } from './types';
import { zhiyeAdapter } from './adapters/zhiyeAdapter';

console.log("AutoApply Content Script V2.1 (Debug Mode) Loaded!");


const adapters = [ zhiyeAdapter, beisenAdapter ];

function executeFill(resumeData: ResumeData) {
  const currentUrl = new URL(window.location.href);
  console.log(`[Debug] 调度器启动，当前URL: ${currentUrl.href}`);
  console.log(`[Debug] 注册了 ${adapters.length} 个适配器。`);

  const activeAdapter = adapters.find(adapter => {
    console.log(`[Debug] 正在测试适配器: ${adapter.constructor.name || 'zhiyeAdapter'}`);
    const isMatch = adapter.matcher(currentUrl);
    console.log(`[Debug] -> 匹配结果: ${isMatch}`);
    return isMatch;
  });

  if (activeAdapter) {
    console.log(`[Debug] 成功匹配到适配器，准备执行填充器...`);
    try {
      activeAdapter.filler(resumeData);
    } catch (error) {
      console.error('[Debug] 填充器执行时发生错误:', error);
    }
  } else {
    console.warn(`[Debug] 未找到适用于 ${currentUrl.hostname} 的适配器。`);
    alert(`抱歉，AutoApply 暂未对当前网站进行专门适配。`);
  }
}

chrome.runtime.onMessage.addListener((request, _sender, sendResponse) => {
  if (request.action === 'fillForm') {
    chrome.storage.local.get('resumeData', (result) => {
      if (result.resumeData) {
        executeFill(result.resumeData);
        sendResponse({ status: '调度完成' });
      } else {
        alert('请先在插件中填写并保存您的简历信息！');
        sendResponse({ status: '失败：未找到简历数据' });
      }
    });
    return true;
  }
});